#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <netinet/in.h>
#include <arpa/inet.h>

typedef struct sockaddr SA;
#define MAXLINE 1024

void dg_cli(FILE* fp, int sockfd, const SA *pservaddr, socklen_t servlen)
{
    int n;
    char sendline[MAXLINE],recvline[MAXLINE+1];
    struct sockaddr *preply_addr;
    preply_addr = malloc(servlen);
    socklen_t len = servlen;
    while(fgets(sendline, MAXLINE, fp) != NULL){
        sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen);
        n = recvfrom(sockfd,recvline,MAXLINE,0,preply_addr,&len);
#if 0
        if(len != servlen || memcmp((void*)pservaddr, (void*)preply_addr, len) != 0){
            printf("reply from %s (ignored)\n", inet_ntoa(((struct sockaddr_in*)preply_addr)->sin_addr));
            continue;
        }
#endif
        recvline[n] = 0;
        fputs(recvline,stdout);
    }
}

void dg_cli_con(FILE* fp, int sockfd)
{
    int n;
    char sendline[MAXLINE],recvline[MAXLINE+1];

    while(fgets(sendline, MAXLINE, fp) != NULL){
        send(sockfd, sendline, strlen(sendline), 0);
        n = recv(sockfd, recvline, MAXLINE, 0);
        recvline[n] = 0;
        fputs(recvline, stdout);
    }
}

int main(int argc, char *argv[])
{
    int sockfd;
    struct sockaddr_in seraddr;
    
    if(argc != 3){
        printf("Usage : %s <IP> <port>\n",argv[0]);
        return -1;
    }

    bzero(&seraddr,sizeof(seraddr));
    seraddr.sin_family = PF_INET;
    seraddr.sin_addr.s_addr = inet_addr(argv[1]);
    seraddr.sin_port = htons(atoi(argv[2]));

    sockfd = socket(PF_INET,SOCK_DGRAM,0);
#if 0
    dg_cli(stdin,sockfd,(SA*)&seraddr,sizeof(seraddr));
#else
    connect(sockfd,(SA*)&seraddr,sizeof(seraddr));
    dg_cli_con(stdin,sockfd);
#endif

    return 0;
}
